<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="listQuery.name" placeholder="市场名称" style="width: 200px;" class="filter-item" />
      <el-input v-model="listQuery.phone" placeholder="电话" style="width: 200px;" class="filter-item" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.a" :value="item.b" />
      </el-select>
      <!-- <el-form-item label="市场类型"> -->
        <el-select clearable v-model="listQuery.category_id" class="filter-item" placeholder="请选择市场类型">
          <el-option v-for="(item, idx) in catypelist" :key="idx" :label="item.name" :value="item.id" />
        </el-select>

        <el-cascader
                :options="areaSelectData"
                @change="handleChange"
                class="full-width"
                size="large"
                clearable
                style="width: 280px;height:36px;top: -4px;"
                placeholder="请选择城市"
              />

      <el-button  class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="getList">
        查询
      </el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button> -->
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      style="width: 100%;overflow-x: auto"
      >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="市场LOGO" width="100px;" align="center">
        <template slot-scope="{row}">
          <img :src="baseimgurl+row.logo_img" alt="" style="width:50px;height:50px;" @click="showvideo(row)">
        </template>
      </el-table-column>
      <el-table-column label="市场名称" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家数量" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.all_store_nu }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>
      <el-table-column label="市场类型" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.category_name }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>
      <el-table-column label="市场简称" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.shot_name }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>
      <el-table-column label="详细地址" width="300px" align="center">
        <template slot-scope="{row}">

          <span>{{row.address || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="营业时间" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.online_time }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>
      <el-table-column label="市场介绍" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.introduce }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>

      <el-table-column label="驳回原因" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.reject_msg||'-' }}</span>
          <!-- <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;"> -->
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ row.status | statusFilter }}
          </el-button> -->
          <el-button v-if="row.status == 2" size="mini" type="success" @click="resetdata(row)">
            通过
          </el-button>
          <!-- <el-button v-if="row.status == 2" size="mini" @click="bohuiData(row)">
            驳回
          </el-button> -->

          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="dialogtitle" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"  :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">


        <el-form-item label="市场名称" >
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="市场类型">
          <el-select clearable v-model="temp.category_id" class="filter-item" placeholder="请选择类型">
            <el-option v-for="(item, idx) in catypelist" :key="idx" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="市场简称" >
          <el-input v-model="temp.shot_name" />
        </el-form-item>

        <el-form-item label="详细地址" >
          <el-input v-model="temp.address" />
        </el-form-item>
        <el-form-item label="营业时间" >
          <el-input v-model="temp.online_time" />
        </el-form-item>
        <el-form-item label="联系电话" >
          <el-input v-model="temp.phone" />
        </el-form-item>

        <el-form-item label="市场LOGO">
          <el-upload
            action=""
            ref="$upload"
            accept="image/jpeg,image/png"
            :auto-upload="false"
            :on-change="onUploadxqimg"
            :show-file-list="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取</el-button>
            <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button> -->
            <div slot="tip" class="el-upload__tip">
              <p v-if="!temp.logo_img">只能上传jpg/png文件，且不能超过10m</p>
              <img v-if="temp.logo_img" style="width:100px;border:1px solid green;height:100px;" :src="baseimgurl+temp.logo_img" alt="">
            </div>

          </el-upload>
        </el-form-item>


        <el-form-item label="市场介绍" >
          <el-input v-model="temp.introduce" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updataForm">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showdialogvideo">
      <img :src="baseimgurl+showimgurl" alt="" style="width:780px;">
    </el-dialog>

    <el-dialog title="市场审核驳回" :visible.sync="isbohui">
      <el-form ref="dataForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="驳回原因" prop="username">
          <el-input v-model="bohuistr" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isbohui = false">
          取消
        </el-button>
        <el-button type="primary" @click="bohuimain()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const __ = {
  formatDate: (date, fmt) => {
    const padLeftZero = (str) => {
      return ('00' + str).substr(str.length)
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  }
}
import { getMarketStore ,  storMarketStore, delMarketStore} from '@/api/store'
import { uploadImg,fetchStorenav } from '@/api/article'

import { regionData, codeToText } from 'element-china-area-data'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import texteditor from '@/views/components/texteditor'
let _catypelist = [];
export default {
  name: 'market',
  components: { Pagination, texteditor },
  filters: {
    formatDate(time) {
      return __.formatDate(new Date(time-0), 'yyyy-MM-dd hh:mm:ss')
    },
    catypefn(type){
      let str = '-';
      _catypelist.forEach(el => {
        if(el.id == type) str = el.title;
      })
      // console.log(_catypelist)
      return str;
    },
  },
  data() {

    return {
      showimgurl: '',
      bohuistr: '',
      areaSelectData: regionData,
      selectedOptions: '',
      showdialogvideo: false,
      isbohui:false,
      baseimgurl: '',
      editorOption: {
        // some quill options
      },
      catypelist : [],
      dialogtitle: '',
      reData:null,
      list: [],
      total: 0,
      calendarTypeOptions: [{a: '待审核',b:2},{a: '已通过',b:1},{a: '驳回',b:3}],
      listQuery: {
        page: 1,
        limit: 20,
        status: undefined,
        name:  undefined,
        phone: undefined,
        category_id: undefined,
        sort: '+id'
      },
      listLoading: false,
      dialogFormVisible: false,
      temp: {
        logo_img: 'http://140.143.146.33/upload/marketImg/f591469b-b980-4ff0-8719-3ef5729933ab.jpg',
        name: '契丹古玩城',
        shot_name: '古玩城',
        address: '内蒙古自治区赤峰市松山区契丹古玩城',
        online_time: '9:00 - 21:00',
        phone: '12312344321',
        introduce: '这里是市场的介绍',
        status: '2',
        category_id: '',
      },
      rules: {
        title: [{ required: true, message: '标题为必填项！', trigger: 'blur' }]
      },
    }


  },
  created() {
    this.getList();
    this.getcatype();
  },
  methods: {
    handleChange(value) {
       // console.log(valu)
       var provinceCode = codeToText[value[0]];
       var cityCode = codeToText[value[1]];
       var orgion = codeToText[value[2]];
       this.listQuery['province'] = provinceCode || '';
       this.listQuery['city'] = cityCode || '';
       this.listQuery['district'] = orgion || '';
     },
    bohuimain() {
      if (!this.bohuistr) {
        return this.$message({
          message: '请填写驳回原因',
          type: 'error'
        })
      }
      const data = this.reData
      this.listLoading = true
      data['status'] = 3
      data['reject_msg'] = this.bohuistr
      storMarketStore(data).then((res) => {
        this.$notify({
          title: 'Success',
          message: '审核成功！',
          type: 'success',
          duration: 2000
        })
        this.bohuistr = '';
        this.isbohui = false;
        this.reData = null;
        this.getList()
      });
    },
    gettypename(id){
      return this.catypelist.find(el => el.id == id);
    },
    getcatype(){
      this.listLoading = true

      fetchStorenav( this.listQuery).then(response => {
        // this.temp.type = response.data[0].title;
        this.catypelist = response;
        // _catypelist = this.catypelist;

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleDelete(row) {
      this.listLoading = true
     

      this.$confirm(`确定要删除此市场 ？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMarketStore({id: row.id}).then((res) => {
          console.log(res);
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
          
          this.getList()
        })

      }).catch(() => {
        this.listLoading = false;
      });
      // this.list.splice(index, 1)
    },
    showvideo(data){
      this.showdialogvideo = true;
      this.showimgurl = data.logo_img;
    },
    updataForm(){

      this.listLoading = true;
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData['category_name'] = this.gettypename(tempData.category_id)['name'];

          storMarketStore(tempData).then(() => {
            this.dialogFormVisible = false;
            this.temp = {
              logo_img: '',
              name: '',
              shot_name: '',
              address: '',
              online_time: '',
              phone: '',
              introduce: '',
              status: '2',
              category_id: '',
            };
            this.$notify({
              title: 'Success',
              message: '操作成功！',
              type: 'success',
              duration: 2000
            });
            this.getList()
          })
        }else{
          this.listLoading = false;
        }
      })
      // console.log(this.temp)
    },
    onEditorBlur(quill) {
        console.log('editor blur!', quill)
      },
      onEditorFocus(quill) {
        console.log('editor focus!', quill)
      },
      onEditorReady(quill) {
        console.log('editor ready!', quill)
      },
    onUploadxqimg(file) {
      const _this = this

      // const isPDF = file.raw.type === 'application/pdf';
      // if (!isPDF) {
      //   return this.$message.error('上传文件只能是 PDF 格式!');
      // }

      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 10;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }


      var formFile = new FormData()
      formFile.append('file', file.raw)
      formFile.append('fileName', 'marketImg')
      this.isupload = true
      uploadImg(formFile).then(response => {

        // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
        _this.temp.logo_img = response.fileUrl
      })
    },

    handleCreate() {
      // this.resetTemp()
      // const text = "内蒙古自治区赤峰市翁牛特旗红山路乌丹第四小学";


      // console.log(values.address.match(regex_a), values.address.match(regex_b),values.address.match(regex_c))
      // return false;
      this.dialogtitle = '添加市场'
      this.temp = {
        logo_img: '',
        name: '',
        shot_name: '',
        address: '',
        online_time: '',
        phone: '',
        introduce: '',
        status: '2',
        category_id: '',
      };
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['$upload'].clearFiles();
      })
    },
    resetdata(data){
      this.listLoading = true;
      this.$confirm(`确定要通过此市场审核 ？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        data['status'] = 1;
        storMarketStore(data).then((res) => {
          this.$notify({
            title: 'Success',
            message: '审核成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })

      }).catch(() => {
        this.listLoading = false;
      });
    },
    bohuiData(data){
      this.bohuistr = '';
      this.isbohui = true;
      this.reData = data;
    },
    getList(){
      getMarketStore(this.listQuery).then(response => {
        console.log(response)
        let list = response.data;
        // this.catypelist.forEach((el, idx) => {
        //   let data = response[idx] || {entry_fee: 0, proxy_fee: 0, user_fee:0};
        //   list.push({category_name: el.name, category_id: el.id, ...data})
        // })
        this.list = list;
        this.total = response.count
        this.listLoading = false
      })
    }
  }
}
</script>
